#region

using System;
using System.Collections.Generic;
using SFML.Graphics;
using SFML.Window;
using SFMLStart.Utilities;
using TimeDRODPOF.TDLib;
using VeeTileEngine2012;
using Utils = SFMLStart.Utilities.Utils;

#endregion

namespace TimeDRODPOF.TDComponents
{
    public class TDCRender : Component
    {
        private static readonly Vector2f DefaultOrigin = new Vector2f(TDLUtils.TileSize/2f, TDLUtils.TileSize/2f);
        public Action OnDraw;

        private bool _needsToPosition;
        private List<Sprite> _sprites;

        public TDCRender(params Sprite[] mSprites)
        {
            Sprites = new List<Sprite>();
            LerpSpeed = 0.35f;

            foreach (var sprite in mSprites) AddSprite(sprite);
        }

        public List<Sprite> Sprites { get { return _sprites; } private set { _sprites = value; } }
        public bool IsLerped { get; set; }
        public float LerpSpeed { get; set; }

        public void AddSprite(Sprite mSprite, bool mSmooth = true)
        {
            mSprite.Texture.Smooth = mSmooth;
            mSprite.Origin = DefaultOrigin;
            _needsToPosition = true;
            Sprites.Add(mSprite);
        }

        public void SetSprite(int mIndex, Sprite mSprite) { Sprites[mIndex] = mSprite; }
        public Sprite GetSprite(int mIndex) { return Sprites[mIndex]; }

        private static Vector2f GetDrawPosition(Vector2f mPosition) { return new Vector2f(mPosition.X*TDLUtils.TileSize + TDLUtils.TileSize/2f, mPosition.Y*TDLUtils.TileSize + TDLUtils.TileSize/2f); }

        public void Draw(RenderTarget mRenderTarget)
        {
            if (Entity.IsOutOfField) return;

            OnDraw.SafeInvoke();

            foreach (var sprite in Sprites)
            {
                if (_needsToPosition) sprite.Position = GetDrawPosition(new Vector2f(X, Y));

                var targetPosition = GetDrawPosition(new Vector2f(Entity.X, Entity.Y));
                var position = targetPosition;
                if (IsLerped)
                    position = Utils.Math.Vectors.Lerp(sprite.Position, targetPosition, LerpSpeed);
                sprite.Position = position;
                mRenderTarget.Draw(sprite);
            }

            if (_needsToPosition) _needsToPosition = false;
        }
    }
}